/*
 * Copyright (c) Deutsche Bank
 */


package org.sunshine.mamadu;

import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author <a href="mailto:anatoliy.evtushenko@db.com">Anatoliy Evtushenko</a>
 * @cvs $Id:$
 */
public class Commons {

    /**
     * If you do not specify an absolute path, the file will be searched automatically in the following locations:
     * <ul>
     * <li>in the current directory</li>
     * <li>in the user home directory</li>
     * <li>in the classpath</li>
     * </ul>
     *
     * @param path path to search
     * @return null if file was not found, else the inputStream of the file.
     * @throws java.io.IOException if the file reading failed.
     */
    public static InputStream getFile(String path) throws IOException {
        LocalLogger.LOGGER.info("Searching file:  " + path);
        File file = new File(path);
        if (file.exists()) {
            LocalLogger.LOGGER.info("File found under path:  " + file.getAbsolutePath());
            return new FileInputStream(file);
        }
        String userHome = System.getProperty("user.home");
        file = new File(userHome + File.separator + path);
        if (file.exists()) {
            LocalLogger.LOGGER.info("File found under path:  " + file.getAbsolutePath());
            return new FileInputStream(file);
        }

        InputStream inputStream = Commons.class.getResourceAsStream(path);
        if (inputStream != null) {
            LocalLogger.LOGGER.info("File found in class path:  " + path);
        } else {
            LocalLogger.LOGGER.info("File '" + path + "'not found.");
        }

        return inputStream;
    }


}
